package com.crane.framework.handler;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * @author:zhanwang
 * @date: 2023/8/21
 * @time: 13:05
 */
public class StringListTypeHandler extends BaseTypeHandler<List<String>> {

  @Override
  public void setNonNullParameter(
      PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
    // 类型直接写死为string 数据库会自行处理
    Array array = ps.getConnection().createArrayOf(JdbcType.VARCHAR.name(), parameter.toArray());
    ps.setArray(i, array);
    array.free();
  }

  @Override
  public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return extractArray(rs.getArray(columnName));
  }

  @Override
  public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return extractArray(rs.getArray(columnIndex));
  }

  @Override
  public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return extractArray(cs.getArray(columnIndex));
  }

  protected List<String> extractArray(Array array) throws SQLException {
    if (array == null) {
      return null;
    }
    Object obj = array.getArray();

    List<String> result = new ArrayList<>();

    if (obj instanceof String[]) {
      result.addAll(Arrays.asList((String[]) obj));
    }
    array.free();
    return result;
  }
}
